package com.smarth.zhizulian.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mobads.BaiduNativeAdPlacement;
import com.google.gson.reflect.TypeToken;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.adapter.NewsAdapter;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventFragment;
import com.smarth.zhizulian.bean.Category;
import com.smarth.zhizulian.bean.News;
import com.smarth.zhizulian.bean.Page;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.exception.NoNetException;
import com.smarth.zhizulian.http.observer.inter.BaseObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.utils.ACache;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.model.ListDataModel;
import com.smarth.zhizulian.utils.listhelper.inter.IDataAdapter;
import com.smarth.zhizulian.utils.listhelper.inter.ResponseSender;
import com.smarth.zhizulian.view.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 18865 on 2017/12/21.
 */

public class CategoryFragment extends EventFragment {
    @BindView(R.id.lv_listview)
    ListView lvListview;
    @BindView(R.id.rv_refresh)
    SmartRefreshLayout rv_refresh;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.tv_nonet)
    TextView tvNonet;

    public static final String INTENT_CATEGORY = "INTENT_CATEGORY";
    @BindView(R.id.tv_ongetdata)
    TextView tvOngetdata;
    private Category mCategory;
    private Disposable mDisposable;
    private Disposable mNoNetDisposable;
    private Disposable mOnGetDataDisposable;
    private RefreshHelper<List<News>> refreshHelper;
    private List<News> data;
    private MyNewsAdapter myNewsAdapter;
    private int randomCoin = 0;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setBKView(R.layout.fragment_category);
        init();
        initListView();

    }

    private void init() {
        mCategory = (Category) getArguments().getSerializable(INTENT_CATEGORY);
    }

    private void initListView() {
        rv_refresh.setOnMultiPurposeListener(new SimpleMultiPurposeListener(){
            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {
                super.onHeaderFinish(header, success);
//                KumaLog.kuma("挖那是");
//                showOnGetData(10);
            }
        });
        refreshHelper = new RefreshHelper<>(mContext, llLoadinglayout, rv_refresh);
        refreshHelper.setDataModel(new ListDataModel<List<News>>() {
            @Override
            public void fetch(final ResponseSender<List<News>> responseSender, int page) {
                KumaHttp.getService().articleReArticleTexts("" + mCategory.getId(), randomCoin, page)
                        .compose(RxCompos.<Page<News>>getBECompos())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                mDisposable = disposable;
                                if (mNoNetDisposable != null && !mNoNetDisposable.isDisposed()) {
                                    KumaLog.kuma("mNoNetDisposable");
                                    mNoNetDisposable.dispose();
                                }
                                if (mOnGetDataDisposable != null && !mOnGetDataDisposable.isDisposed()) {
                                    KumaLog.kuma("mOnGetDataDisposable");
                                    mOnGetDataDisposable.dispose();
                                }
                                tvOngetdata.setVisibility(View.GONE);
                                tvNonet.setVisibility(View.GONE);
                            }
                        })
                        .subscribe(new BaseObserver<Page<News>>(mContext) {
                            @Override
                            public void onNext(Page<News> newsPage) {
                                responseSender.sendData(newsPage.getList());
                                randomCoin = newsPage.getCount();
                                setmPage(newsPage.getPageNo());
                                setmMaxPage(newsPage.getPageNum());
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                if (myNewsAdapter.isDataEmpty()) {
                                    responseSender.sendError((Exception) e);
                                } else {
                                    refreshHelper.finishContent(0);
                                }
                            }

                            @Override
                            public void onErrorNoNet(NoNetException e) {
                                showNoNet();
                            }
                        });
            }
        });
        data = new ArrayList<>();
        myNewsAdapter = new MyNewsAdapter(getContext(), data);
        refreshHelper.setDataAdapter(myNewsAdapter, R.id.lv_listview);
        try {
            String json = ACache.get(mContext).getAsString(BaseConfig.ACache.NEWS + mCategory.getName());
            List<News> newses = GsonUtils.fromJson(json, new TypeToken<List<News>>() {
            });
            if (newses != null && newses.size() > 0) {
                refreshHelper.sendData(newses);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        refreshHelper.refresh();
    }

    public static CategoryFragment getInstance(Category category) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putSerializable(INTENT_CATEGORY, category);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            KumaLog.kuma("mDisposable");
            mDisposable.dispose();
        }
        if (mNoNetDisposable != null && !mNoNetDisposable.isDisposed()) {
            KumaLog.kuma("mNoNetDisposable");
            mNoNetDisposable.dispose();
        }
        if (mOnGetDataDisposable != null && !mOnGetDataDisposable.isDisposed()) {
            KumaLog.kuma("mOnGetDataDisposable");
            mOnGetDataDisposable.dispose();
        }
    }

    @Override
    protected void onLogin(EventBean eb) {
        refreshHelper.refresh();
    }

    public class MyNewsAdapter extends NewsAdapter implements IDataAdapter<List<News>> {

        public MyNewsAdapter(Context context, List<?> datas) {
            super(context, datas);
        }

        @Override
        public void onGetData(List<News> news, boolean isRefresh) {
            if (isRefresh) {
                mDatas.clear();
                ACache.get(mContext).put(BaseConfig.ACache.NEWS + mCategory.getName(), GsonUtils.toJson(news));
                showOnGetData(news.size());
            }
            mDatas.addAll(news);
            notifyDataSetChanged();

        }

        @Override
        public boolean isDataEmpty() {
            return mDatas == null || mDatas.size() == 0;
        }

        @Override
        public List<News> getMyData() {
            return mDatas;
        }

    }

    private void showNoNet() {
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mNoNetDisposable = disposable;
                        tvNonet.setVisibility(View.VISIBLE);
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        tvNonet.setVisibility(View.GONE);
                    }
                });
    }

    private void showOnGetData(final int num) {
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mOnGetDataDisposable = disposable;
                        tvOngetdata.setText("健康头条为您推荐" + num + "条更新");
                        tvOngetdata.setVisibility(View.VISIBLE);
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        tvOngetdata.setVisibility(View.GONE);
                    }
                });
    }

    @Subscriber(tag = "CategoryFragment")
    private void onEvent(EventBean eb) {
        switch (eb.getCode()) {
            case BaseConfig.EventCode.REFRESH:
                lvListview.setSelection(0);
                refreshHelper.refresh();
                break;
        }
    }
}
